$(function () {
  let layer = layui.layer;
  //获取用户信息
  getInfo();

  $("#btnLogout").on("click", function () {
    layer.confirm("is not?", { icon: 3, title: "提示" }, function (index) {
      localStorage.removeItem("token");
      location.href = "./login.html";

      layer.close(index);
    });
  });
});

function getInfo() {
  $.ajax({
    url: "/my/userinfo",
    headers: { Authorization: localStorage.getItem("token") },

    success: function (res) {
      if (res.status !== 0) {
        console.log(res);
        return layer.msg(res.message);
      }

      //渲染用户图像
      renderAvater(res.data);
    },

    complete: function (res) {
      if (
        res.responseJSON.status === 1 &&
        res.responseJSON.message === "身份认证失败！"
      ) {
        localStorage.removeItem("token");
        location.href = "./login.html";
      }
    },
  });
}

function renderAvater(user) {
  let name = user.nickname || user.username;
  $(".welcome").html("欢迎&nbsp;&nbsp;" + name);
  if (user.user_pic) {
    $(".layui-nav-img").attr("src", user.user_pic).show();
    $(".text-avatar").hide();
  } else {
    $(".text-avatar").html(name[0].toUpperCase()).show();
    $(".layui-nav-img").hide();
  }
}
